package day02;

import util.JdbcUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class TestJDBC3 {

    public static void main(String[] args) {
//        insert();
//        update();
//        delete();
        select();
    }



    public static void insert(){

        Connection con=null;
        PreparedStatement ps=null;
        try{
            con= JdbcUtil.getConnection();

            String sql=new StringBuffer()
                    .append("insert into t_user ")
                    .append("    (name) ")
                    .append("values ")
                    .append("    (?) ")
                    .toString();

            ps=con.prepareStatement(sql);


            ps.setString(1,"fff");

            ps.executeUpdate();

        }catch (Exception e){
            e.printStackTrace();
        }finally{
            JdbcUtil.close(null,ps,con);
        }


    }

    public static void update(){
        Connection con=null;
        PreparedStatement ps=null;
        try{
            con= JdbcUtil.getConnection();

            String sql=new StringBuffer()
                    .append("update t_user ")
                    .append("set name=? ")
                    .append("where id=? ")
                    .toString();

            ps=con.prepareStatement(sql);

            ps.setString(1,"abc");
            ps.setInt(2,2);

            ps.executeUpdate();

        }catch (Exception e){
            e.printStackTrace();
        }finally{
            JdbcUtil.close(null,ps,con);
        }
    }

    public static void delete(){
        Connection con=null;
        PreparedStatement ps=null;
        try{
            con= JdbcUtil.getConnection();

            String sql=new StringBuffer()
                    .append("delete from t_user ")
                    .append("where id=? ")
                    .toString();

            ps=con.prepareStatement(sql);

            ps.setInt(1,2);

            ps.executeUpdate();

        }catch (Exception e){
            e.printStackTrace();
        }finally{
            JdbcUtil.close(null,ps,con);
        }
    }

    public static void select(){
        Connection con=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        try{
            con= JdbcUtil.getConnection();

            String sql=new StringBuffer()
                    .append("select * ")
                    .append("from t_user ")
                    .toString();

            ps=con.prepareStatement(sql);

            rs=ps.executeQuery();

            while (rs.next()) {
                System.out.println(rs.getInt("id")+"\t"+rs.getString("name"));
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally{
            JdbcUtil.close(rs,ps,con);
        }
    }
}
